<template>
  <div>
    <!-- 标题 -->
    <el-card class="content scrollbar">
      <el-form class="search ml20" :inline="true" label-suffix="：" size="mini">
        <el-form-item label="配方信息">
          <el-input
            v-model="search.formulas"
            clearable
            class="w280"
            placeholder="配方名称/编码/三方编码/助记码"
            @keyup.enter.native="getList('search')"
          />
        </el-form-item>
        <el-form-item label="科室维度">
          <MultipleSelect
            ref="dept"
            v-model="search.deptIds"
            name="dept"
            width="200"
            :options="multipleSelectOptions"
            multiple
            :data="options.dept"
          >
            <!-- <option
              v-for="item in options.dept"
              :key="item.id"
              :value="item.id"
            >
              {{ item.dictValue }}
            </option> -->
          </MultipleSelect>
        </el-form-item>
        <el-form-item label="疾病维度">
          <MultipleSelect
            ref="disease"
            v-model="search.diseaseIds"
            name="disease"
            width="200"
            :options="multipleSelectOptions"
            multiple
            :data="options.disease"
          />
        </el-form-item>
        <el-form-item label="医生维度">
          <MultipleSelect
            ref="doctor"
            v-model="search.doctorIds"
            name="doctor"
            width="200"
            :options="doctorMultipleSelectOptions"
            multiple
            :data="options.doctor"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="search.status" @change="getList('search')">
            <el-radio label="">全部</el-radio>
            <el-radio :label="2">启用</el-radio>
            <el-radio :label="3">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <el-form class="search ml20" :inline="true" label-suffix="：" size="mini">
        <el-form-item>
          <el-button type="primary" @click="getList('search')">确认 </el-button>
          <el-button @click="searchReset">重置 </el-button>
        </el-form-item>
        <el-form-item class="ml50">
          <el-button
            v-if="permission['001005014002']"
            type="primary"
            @click="detailBtn('新增', {})"
          >新增
          </el-button>
          <el-button
            v-if="permission['001005014007']"
            type="primary"
            @click="dialogVisible = true"
          >导入
          </el-button>
          <el-button
            v-if="permission['001005014008']"
            type="primary"
            :disabled="selectionList.length == 0"
            @click="exportDialogVisible = true"
          >导出
          </el-button>
        </el-form-item>
        <el-form-item class="ml200">
          <el-button
            type="primary"
            disabled
          >已选择{{ selectionList.length }}条</el-button>
          <el-button
            type="primary"
            :disabled="selectionList.length == 0"
            @click="batchSetDeptDialogShow = true"
          >批量设置科室
          </el-button>
          <el-button
            type="primary"
            :disabled="selectionList.length == 0"
            @click="batchSetDiseaseDialogShow = true"
          >批量设置疾病
          </el-button>
          <el-button
            type="primary"
            :disabled="selectionList.length == 0"
            @click="batchSetDoctorDialogShow = true"
          >批量设置医生
          </el-button>
        </el-form-item>
      </el-form>
      <el-table
        ref="table"
        :data="list"
        size="small"
        :height="tableHeight"
        :cell-style="$style.cellStyle"
        :header-cell-style="$style.rowClass"
        @row-click="handleRowClick"
        @selection-change="handleSelectionChange"
      >
        <ElTableColumn type="selection" width="50" />
        <ElTableColumn label="序号" type="index" width="50" />
        <ElTableColumn label="配方名称" prop="formulaName" />
        <ElTableColumn label="版本号" prop="versionNo" />
        <ElTableColumn label="药品编码" prop="drugCode" />
        <ElTableColumn label="三方编码" prop="drugThirdCode" />
        <ElTableColumn label="剂型种类" prop="medicamentTypeName" />
        <ElTableColumn label="科室维度" prop="dept" />
        <ElTableColumn label="疾病维度" prop="disease" />
        <ElTableColumn label="医生维度" prop="doctor" />
        <ElTableColumn label="创建时间" prop="createTime" />
        <ElTableColumn label="创建人" prop="createBy" />
        <ElTableColumn label="状态" width="220">
          <template slot-scope="{ row }">
            <span>{{ row.statusEnum != 2 ? "禁用" : "启用" }}</span>
          </template>
        </ElTableColumn>
        <ElTableColumn label="操作" width="220">
          <template slot-scope="{ row }">
            <el-button
              v-if="permission['001005014003']"
              type="primary"
              size="mini"
              @click="detailBtn('修改', row)"
            >修改</el-button>
            <el-button
              v-if="permission['001005014004'] && row.statusEnum != 2"
              type="success"
              size="mini"
              class="mr20"
              @click="hint('启用', `启用${row.formulaName}`, row)"
            >
              启用
            </el-button>
            <el-button
              v-if="permission['001005014005'] && row.statusEnum == 2"
              type="warning"
              size="mini"
              class="mr20"
              @click="hint('禁用', `禁用${row.formulaName}`, row)"
            >禁用
            </el-button>
            <!-- <el-button
              size="mini"
              @click="hint('del','此操作将永久删除该类型',row)"
            >删除</el-button>
            <el-button size="mini" @click="detailBtn('详情',row)">详情</el-button> -->
            <el-dropdown
              @command="
                (command) => {
                  handleCommand(command, row);
                }
              "
            >
              <span class="el-dropdown-link">
                <i class="el-icon-more" />
              </span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item v-if="permission['001005014006']" command="删除">删除</el-dropdown-item>
                <el-dropdown-item command="详情">详情</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </ElTableColumn>
      </el-table>
      <pagination
        class="page tc mt10"
        :total="page.total"
        :page.sync="page.pageNum"
        :limit.sync="page.pageSize"
        @pagination="getList"
      />
    </el-card>
    <el-dialog
      title="导入"
      :close-on-click-modal="false"
      :visible.sync="dialogVisible"
      width="40%"
    >
      <el-form
        class="search ml20"
        :inline="true"
        label-position="right"
        label-width="100px"
        size="mini"
      >
        <el-form-item label="下载模板">
          <el-button
            type="text"
            class="w500 tl"
            @click="hint('下载模板', `下载模板`)"
          >导入模板</el-button>
        </el-form-item>
        <el-form-item label="选择文件">
          <fileUpload
            v-if="dialogVisible"
            file-type="personnel"
            @handleAvatarSuccess="handleAvatarSuccess"
          />
        </el-form-item>
      </el-form>
      <!-- <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="dialogVisible = false">取 消</el-button>
        <el-button size="mini" type="primary" @click="dialogVisible = false">确 定</el-button>
      </span> -->
    </el-dialog>
    <el-dialog title="导入提示" :visible.sync="tipVisible" width="500px">
      <div style="font-size: 20px; font-weight: 700; margin-bottom: 10px">
        {{ tipData.head }}
      </div>
      <div
        class="tipDataList"
        style="
          height: 300px;
          overflow: hidden auto;
          border: 1px solid #efefef;
          padding: 5px;
        "
      >
        <div
          v-for="(item, index) in tipData.body"
          :key="index"
          style="font-size: 16px; line-height: 25px"
        >
          {{ item }}
        </div>
      </div>
    </el-dialog>
    <el-dialog
      title="选择价格院区"
      :close-on-click-modal="false"
      :visible.sync="exportDialogVisible"
      width="400px"
    >
      <el-form ref="detail" label-position="left">
        <el-form-item size="mini" label="价格院区">
          <el-select
            v-model="yardId"
            filterable
            clearable
            multiple
            placeholder="请选择"
            value-key="id"
          >
            <el-option
              v-for="item in options.yard"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button
          size="mini"
          @click="exportDialogVisible = false"
        >取 消</el-button>
        <el-button
          size="mini"
          type="primary"
          @click="exportList"
        >确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      center
      width="500px"
      title="批量设置科室"
      :visible.sync="batchSetDeptDialogShow"
    >
      <el-checkbox
        v-model="batchSetDeptCheckAll"
        :indeterminate="batchSetDeptIsIndeterminate"
        @change="handleBatchSetDeptCheckAllChange"
      >全选</el-checkbox>
      <el-checkbox-group
        v-model="batchSetDeptList"
        @change="handleBatchSetDeptListChange"
      >
        <el-checkbox
          v-for="item in options.dept"
          :key="item.id"
          :label="item.id"
        >{{ item.dictValue }}</el-checkbox>
      </el-checkbox-group>
      <div slot="footer">
        <el-button
          type="primary"
          @click="dimensionAddAndDelect(1)"
        >确 定</el-button>
        <el-button @click="batchSetDeptDialogShow = false">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog
      center
      width="500px"
      title="批量设置疾病"
      :visible.sync="batchSetDiseaseDialogShow"
    >
      <el-checkbox
        v-model="batchSetDiseaseCheckAll"
        :indeterminate="batchSetDiseaseIsIndeterminate"
        @change="handleBatchSetDiseaseCheckAllChange"
      >全选</el-checkbox>
      <el-checkbox-group
        v-model="batchSetDiseaseList"
        @change="handleBatchSetDiseaseListChange"
      >
        <el-checkbox
          v-for="item in options.disease"
          :key="item.id"
          :label="item.id"
        >{{ item.dictValue }}</el-checkbox>
      </el-checkbox-group>
      <div slot="footer">
        <el-button
          type="primary"
          @click="dimensionAddAndDelect(2)"
        >确 定</el-button>
        <el-button @click="batchSetDiseaseDialogShow = false">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog
      center
      width="500px"
      title="批量设置医生"
      :visible.sync="batchSetDoctorDialogShow"
    >
      <el-checkbox
        v-model="batchSetDoctorCheckAll"
        :indeterminate="batchSetDoctorIsIndeterminate"
        @change="handleBatchSetDoctorCheckAllChange"
      >全选</el-checkbox>
      <el-checkbox-group
        v-model="batchSetDoctorList"
        @change="handleBatchSetDoctorListChange"
      >
        <el-checkbox
          v-for="item in options.doctor"
          :key="item.person_id"
          :label="item.person_id"
        >{{ item.person_name }}</el-checkbox>
      </el-checkbox-group>
      <div slot="footer">
        <el-button
          type="primary"
          @click="dimensionAddAndDelect(3)"
        >确 定</el-button>
        <el-button @click="batchSetDoctorDialogShow = false">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import pagination from '@/components/Pagination';
import { dictsPullList } from '@/api/dictionaries';
import { yardPullList } from '@/api/courtyardAdmin';
import fileUpload from '@/components/Upload/fileUpload';
import {
  formulaList,
  updateStatus,
  registerDel,
  businesExport,
  dimensionQuery,
  dimensionAddAndDelect
} from '@/api/formula';
import { mapGetters } from 'vuex';
class Page {
  total = 0;
  pageNum = 1;
  pageSize = 30;
}
class Search {
  formulas = '';
  giftTypeIds = [];
  applyHospitalAreaIds = [];
  status = '';
  deptIds = [];
  diseaseIds = [];
  doctorIds = [];
}

class Options {
  giftType = {};
  yard = [];
  options = [
    { id: 1, name: '选项一' },
    { id: 2, name: '选项二' },
    { id: 3, name: '选项三' },
    { id: 4, name: '选项四' }
  ];
  dept = []; // 科室维度
  disease = []; // 疾病维度
  doctor = []; // 医生维度
}
export default {
  components: {
    pagination,
    fileUpload
  },
  data() {
    return {
      multipleSelectOptions: {
        formatSelectAll: function name(params) {
          return '全部';
        },
        // filter: true, // 开启过滤
        multiple: true // 一行显示多个选项
      },
      doctorMultipleSelectOptions: {
        formatSelectAll: function name(params) {
          return '公共';
        },
        filter: true, // 开启过滤
        multiple: true // 一行显示多个选项
      },
      search: new Search(), // 检索条件
      options: new Options(), // 选项
      page: new Page(), // 分页
      dialogVisible: false,
      list: [], // 列表
      tableHeight: 200,
      yardId: '',
      exportDialogVisible: false,
      selectionList: [],
      exportUrl: '',
      tipVisible: false,
      tipData: {},
      batchSetDeptDialogShow: false,
      batchSetDeptList: [],
      batchSetDeptCheckAll: false,
      batchSetDeptIsIndeterminate: true,
      batchSetDiseaseDialogShow: false,
      batchSetDiseaseList: [],
      batchSetDiseaseCheckAll: false,
      batchSetDiseaseIsIndeterminate: true,
      batchSetDoctorDialogShow: false,
      batchSetDoctorList: [],
      batchSetDoctorCheckAll: false,
      batchSetDoctorIsIndeterminate: true
    };
  },

  computed: {
    ...mapGetters(['permission']),
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids;
    }
  },
  watch: {
    'search.deptIds': function name(params) {
      console.log('watch search.deptIds');
    }
  },
  mounted() {
    this.getOptions();
    // 初始化表格高度
    this.$nextTick(() => {
      this.initTableHeight();
    });
    window.addEventListener('resize', this.initTableHeight);
    this.common.initWebSocket(this.global_callback);
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.initTableHeight);
  },
  methods: {
    handleBatchSetDoctorCheckAllChange(val) {
      this.batchSetDoctorList = val
        ? this.options.doctor.map((item) => item.person_id)
        : [];
      this.batchSetDoctorIsIndeterminate = false;
    },
    handleBatchSetDoctorListChange(value) {
      console.log(value);
      let checkedCount = value.length;
      this.batchSetDoctorCheckAll =
        checkedCount === this.options.doctor.length;
      this.batchSetDoctorIsIndeterminate =
        checkedCount > 0 && checkedCount < this.options.doctor.length;
    },
    handleBatchSetDiseaseCheckAllChange(val) {
      this.batchSetDiseaseList = val
        ? this.options.disease.map((item) => item.id)
        : [];
      this.batchSetDiseaseIsIndeterminate = false;
    },
    handleBatchSetDiseaseListChange(value) {
      console.log(value);
      let checkedCount = value.length;
      this.batchSetDiseaseCheckAll =
        checkedCount === this.options.disease.length;
      this.batchSetDiseaseIsIndeterminate =
        checkedCount > 0 && checkedCount < this.options.disease.length;
    },
    handleBatchSetDeptCheckAllChange(val) {
      this.batchSetDeptList = val
        ? this.options.dept.map((item) => item.id)
        : [];
      this.batchSetDeptIsIndeterminate = false;
    },
    handleBatchSetDeptListChange(value) {
      console.log(value);
      let checkedCount = value.length;
      this.batchSetDeptCheckAll = checkedCount === this.options.dept.length;
      this.batchSetDeptIsIndeterminate =
        checkedCount > 0 && checkedCount < this.options.dept.length;
    },
    dimensionAddAndDelect(dimension_type) {
      /* 组装数据↓ */
      let dimensionList = [];
      let selectedOpitons = [];
      if (dimension_type == 1) {
        selectedOpitons = this.options.dept.filter((item) =>
          this.batchSetDeptList.some((checkedItem) => checkedItem === item.id)
        );
      } else if (dimension_type == 2) {
        selectedOpitons = this.options.disease.filter((item) =>
          this.batchSetDiseaseList.some(
            (checkedItem) => checkedItem === item.id
          )
        );
      } else {
        selectedOpitons = this.options.doctor.filter((item) =>
          this.batchSetDoctorList.some((checkedItem) => checkedItem === item.person_id)
        );
      }
      this.selectionList.forEach((item) => {
        selectedOpitons.forEach((option) => {
          dimensionList.push({
            dimension_code: option.id || option.person_id,
            dimension_name: option.dictValue || option.person_name,
            formula_code: item.drugCode,
            dimension_id: item.drugCode,
            dimension_type
          });
        });
      });
      // '维度类型(1:科室，2:疾病，3:医生)';
      let data = {
        dimension_id: this.selectionList.map((item) => item.drugCode),
        dimension_type: [dimension_type],
        dimensionList
      };
      /* 组装数据↑ */
      dimensionAddAndDelect(data).then((res) => {
        if (res.code === 200) {
          switch (dimension_type) {
            case 1:
              this.batchSetDeptDialogShow = false;
              break;
            case 2:
              this.batchSetDiseaseDialogShow = false;
              break;
            case 3:
              this.batchSetDoctorDialogShow = false;
              break;
            default:
              break;
          }
          this.$notification('操作成功', 'success', res.msg);
          this.getList();
        } else {
          this.$notification('操作失败', 'success', res.msg);
        }
      });
    },
    batchSetDeptListChange(e) {
      console.log(this.batchSetDeptList);
    },
    multipleSelectChange(name) {
      this.search[name + 'Ids'] = this.$refs[name].getSelects();
    },
    batchSetDialogShow(name) {},
    // 初始化表格高度
    initTableHeight() {
      if (!this.$refs.table) {
        this.$nextTick(() => {
          this.initTableHeight();
        });
        return;
      }
      const tableHeight =
        window.innerHeight -
        this.$refs.table.$el.getBoundingClientRect().top -
        70;
      this.tableHeight = Math.max(tableHeight, 200);
    },
    async getOptions() {
      const { data } = await dictsPullList({
        dicTypes: ['giftCategory', 'dimension', 'dimensionDeptIds']
      });
      this.options.giftType = data.giftCategory;
      this.options.dept = data.dimensionDeptIds.map(item => {
        item.text = item.dictValue;
        item.value = item.id;
        return item;
      });
      this.options.disease = data.dimension.map(item => {
        item.text = item.dictValue;
        item.value = item.id;
        return item;
      });
      const yard = await yardPullList({ yardTypeIds: [37, 38] });
      this.options.yard = yard ? yard.data : [];
      let res = await dimensionQuery();
      this.options.doctor = res.data.list.map(item => {
        item.text = item.person_name;
        item.value = item.person_id;
        return item;
      }) || [];
      console.log(this.options.doctor);
      this.getList();
    },
    async getList() {
      try {
        this.search.dimension_codes = this.search.deptIds.concat(this.search.diseaseIds, this.search.doctorIds);
        const { data } = await formulaList({
          pageNum: this.page.pageNum,
          pageSize: this.page.pageSize,
          ...this.search
        });
        // console.log(data);
        this.list = data.list.map(item => {
          item.dept = item.dimensionListVO.find(vo => vo.dimension_type === 1)?.dimension_name;
          item.disease = item.dimensionListVO.find(vo => vo.dimension_type === 2)?.dimension_name;
          item.doctor = item.dimensionListVO.find(vo => vo.dimension_type === 3)?.dimension_name;
          return item;
        });
        this.page.total = data.total;
      } catch (e) {
        this.page.total = 0;
        this.list = [];
      }
    },

    // 搜索重置
    searchReset() {
      this.search = new Search();
      // this.search.statuss = [0, 1];
      this.getList();
    },
    // 详情跳转
    detailBtn(nameType, row) {
      this.$router.push({
        path: '/archives/formula/detail',
        query: { nameType: nameType, id: row.id }
      });
    },
    // 操作按钮
    handleCommand(type, row) {
      switch (type) {
        case '详情':
          this.detailBtn('详情', row);
          break;
        case '删除':
          this.hint('del', '此操作将永久删除该类型', row);
          break;
      }
    },
    // 确认提示
    hint(status, hintText, row) {
      this.$confirm(`${hintText}, 是否确认?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          switch (status) {
            case 'del':
              this.delRow(row);
              break;
            case '禁用':
              this.stateChange(row);
              break;
            case '启用':
              this.stateChange(row);
              break;
            case '导出':
              this.exportDialogVisible = true;
              // this.exportList();
              break;
            case '下载模板':
              this.template();
              break;
          }
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          });
        });
    },
    // 删除
    async delRow(row) {
      const res = await registerDel({
        id: row.id
      });
      this.$notification('操作成功', 'success', res.msg);
      this.getList();
    },
    // 状态更改
    async stateChange(row) {
      let status = row.statusEnum == 2 ? 3 : 2;
      const res = await updateStatus({
        status: status,
        id: row.id
      });
      this.$notification('操作成功', 'success', res.msg);
      this.getList();
    },
    // 改变表格选中状态
    handleSelectionChange(val) {
      this.selectionList = val;
      console.log(this.selectionList);
    },
    // 点击行
    handleRowClick(row) {
      this.$refs.table.toggleRowSelection(row);
    },
    // 导出
    async exportList() {
      if (!this.yardId) {
        this.$notification('警告', 'warning', '请选择价格院区');
        return;
      }

      const blob = await businesExport({ yardIds: this.yardId, ids: this.ids });
      this.exportDialogVisible = false;
      if (blob.size > 0) {
        // this.exportUrl = res.data;
        // window.open(url);
        const link = document.createElement('a');
        link.href = window.URL.createObjectURL(blob);
        link.download = '药品配方.xlsx';
        document.body.appendChild(link);
        link.click();
        window.setTimeout(() => {
          window.URL.revokeObjectURL(blob);
          document.body.removeChild(link);
        }, 0);
      }
    },
    // 下载模板
    async template() {
      let url = window.server.SERVER_API[2].temolate + '配方管理导入模板.xlsx';
      window.open(url);
      // console.log(window.server.SERVER_API[2].temolate);
    },
    global_callback(msg) {
      msg = JSON.parse(msg);
      if (msg.socketTypeEnum == 'EXCEL_EXPORT_FINISH') {
        let url = window.server.SERVER_API[1].excel + this.exportUrl;
        window.open(url);
      } else if (msg.socketTypeEnum == 'EXCEL_EXPORT_ING') {
        this.$notification('提示', 'info', msg.message);
      }
    },
    // 上传图片成功回调
    handleAvatarSuccess(res) {
      console.log(res);
      if (res) {
        this.getList();
        if (res.code == 200) {
          this.$notification('操作成功', 'success', res.msg);
          this.dialogVisible = false;
        } else if (res.code != 500) {
          this.tipData = JSON.parse(res.msg);
          this.tipVisible = true;
          this.dialogVisible = false;
        } else {
          this.$notification('操作失败', 'error', res.msg);
        }
      } else {
        this.$message.info(res.msg);
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.content {
  // height: calc(100% - 56px);
  // overflow-y: hidden;

  // height: 85vh;
  ::v-deep img {
    width: 50px;
    border-radius: 4px;
    margin-top: 6px;
  }
}
.content:hover {
  overflow-y: auto;
}
</style>
